﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RrslLite.Net.Ioc;
using RrslLite.Net.Messages;

namespace RrslLite.Host
{
    public class MessageService
    {
        protected Message[] ProcessMessages(Message[] messages)
        {
            var result = new List<Message>();

            foreach (var wcfMessage in messages)
            {
                result.Add(InvokeOperation(wcfMessage));
            }

            return result.ToArray();
        }

        protected virtual Message InvokeOperation(Message message)
        {
            var result = message;

			try
			{
				var objectFromFactory = IocHelper.ContainerInstance.Resolve<IRegisterable>(message.OperationContainerName);
				Type objectType = objectFromFactory.GetType();

				Type[] methodAttributesTypes =
					message.OperationParameters.Select(selector => selector.Value.GetType()).ToArray();

				var method = objectType.GetMethod(message.OperationName, methodAttributesTypes);
				var parameters = method.GetParameters();
				var filledParameters = new List<object>();

				if (message.OperationParameters != null)
				{
					filledParameters.AddRange(parameters.Select(methodParameter => message.OperationParameters[methodParameter.Name]));
				}

				result.Result = method.Invoke(objectFromFactory, filledParameters.ToArray());
			}
			catch (Exception e)
			{
				result.ContainsException = true;
				if (e.InnerException != null)
					result.Result = e.InnerException.Message;

				OnExeption(e, message);
			}
			finally
			{
				if (message != null && message.OperationParameters != null)
				{
					message.OperationParameters.Clear();
				}				
			}
			return result;
        }

		protected virtual void OnExeption(Exception e, Message message)
		{
			
		}
    }
}
